package com.jy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jy.common.enums.ResponseWrapper;
import com.jy.common.enums.ResultEnum;
import com.jy.common.model.login.BackstageLogin;
import com.jy.common.model.login.LoginByCodeParam;
import com.jy.common.model.login.ReceptionLoginParam;
import com.jy.common.model.login.ReceptionLoginResult;
import com.jy.common.model.user.param.UpdateAvatar;
import com.jy.common.model.user.param.UpdateUserBgDto;
import com.jy.common.tool.CommonTool;
import com.jy.common.tool.JwtUtil;
import com.jy.common.tool.ToolForDateTime;
import com.jy.entity.*;
import com.jy.mapper.*;
import com.jy.service.UserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author fzg
 * @since 2024-11-08
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final UserMapper userMapper;
    private final UserFollowMapper userFollowMapper;
    private final DynamicMapper dynamicMapper;
    private final ThumbsUpMapper thumbsUpMapper;
    private final CollectMapper collectMapper;
    private final GoodsMapper goodsMapper;


    @Value("${server.base-url}")
    private String serverBaseUrl;

    public UserServiceImpl(UserMapper userMapper, UserFollowMapper userFollowMapper, DynamicMapper dynamicMapper, ThumbsUpMapper thumbsUpMapper, CollectMapper collectMapper, GoodsMapper goodsMapper) {
        this.userMapper = userMapper;
        this.userFollowMapper = userFollowMapper;
        this.dynamicMapper = dynamicMapper;
        this.thumbsUpMapper = thumbsUpMapper;
        this.collectMapper = collectMapper;
        this.goodsMapper = goodsMapper;
    }

    @Override
    public ResponseWrapper receptionLogin(ReceptionLoginParam param) {

        // 返回结果
        ReceptionLoginResult result = new ReceptionLoginResult();

        // 通过手机号查询
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getPhone, param.getPhone()));
        if (user == null) {
            // 返回错误信息，先用验证码登录
            return ResponseWrapper.markCustomError("手机号不存在");
        }else {

            // 手机号存在，先检查密码是否正确
            if(user.getPassword().equals(param.getPassword())){
                // 制作token
                Map<String, String> map = new HashMap<>();
                map.put("aid", user.getAid().toString());
                String token = JwtUtil.getToken(map);
                result.setToken(token);
                return ResponseWrapper.markCustomSuccess("登陆成功！",result);
            }else {
                return ResponseWrapper.markCustomError("密码错误！");
            }
        }

    }

    @Override
    public ResponseWrapper getUserInfo(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token!= null) {
            Integer userAid = JwtUtil.getTokenId(token);
            // 根据用户aid查询用户信息
            User user = userMapper.selectById(userAid);
            return ResponseWrapper.markSuccess(user);
        }else {
            return ResponseWrapper.markCustomError("token为空");
        }
    }

    @Override
    public ResponseWrapper uploadImg(String filePath) {
        // 生成HTTP URL
        String pictureUrl = serverBaseUrl + filePath;

//        if (token!= null) {
//            Integer userAid = JwtUtil.getTokenId(token);
            // 根据用户aid查询用户信息
            User user = userMapper.selectById(1);
            user.setBgImageUrl(pictureUrl);
            int update = userMapper.updateById(user);
            if (update > 0) {
                return ResponseWrapper.markCustomSuccess("图片上传成功",user);
            }else {
                return ResponseWrapper.markCustomError("图片上传失败");
            }
//        }else {
//            return ResponseWrapper.markCustomError("图片上传失败，token为空");
//        }
    }

    @Override
    public ResponseWrapper disLikeThisDynamicApi(Integer userAidByToken, Integer dynamicAid) {

        // 添加用户的不喜欢动态
        User user = userMapper.selectById(userAidByToken);
        String dislikeDynamicAids = user.getDislikeDynamicAids();
        if (dislikeDynamicAids != null) {
            user.setDislikeDynamicAids(dislikeDynamicAids + "," + dynamicAid);
        }else{
            // 直接添加
            user.setDislikeDynamicAids(dynamicAid.toString());
        }
        userMapper.updateById(user);
        return ResponseWrapper.markCustomSuccess("已为你隐藏");
    }

    @Override
    public ResponseWrapper backstageLogin(BackstageLogin param) {
//        System.out.println("用户名：" + param.getUsername());
//        System.out.println("密码：" + param.getPassword());
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getName, param.getUsername())
                .eq(User::getPassword, param.getPassword())
        );
        if (user != null) {
            // 制作token
            Map<String, String> map = new HashMap<>();
            map.put("aid", user.getAid().toString());
            String token = JwtUtil.getToken(map);
            HashMap<String, Object> result = new HashMap<>();
            result.put("token", token);
            return ResponseWrapper.markSuccess(result);
        }else {
            return ResponseWrapper.markError(ResultEnum.LOGIN_ERROR);
        }
    }

    @Override
    public ResponseWrapper updateUserBg(Integer userAidByToken, UpdateUserBgDto param) {

        User user = userMapper.selectById(userAidByToken);
        user.setBgImageUrl(param.getUserBg());
        int updateUserBg = userMapper.updateById(user);
        return updateUserBg > 0 ? ResponseWrapper.markSuccess() : ResponseWrapper.markError();
    }

    @Override
    public ResponseWrapper updateAvatar(Integer userAidByToken, UpdateAvatar param) {

        User user = userMapper.selectById(userAidByToken);
        user.setAvatar(param.getAvatar());
        int updateById = userMapper.updateById(user);
        if (updateById > 0){
            return ResponseWrapper.markSuccess();
        }else {
            return ResponseWrapper.markError();
        }

    }

    @Override
    public ResponseWrapper getUserAllInfoInSetting(Integer userAidByToken) {

        User user = userMapper.selectById(userAidByToken);

        HashMap<String, Object> myInfo = new HashMap<>();
        myInfo.put("BgImg",checkEmpty(user.getBgImageUrl()));
        myInfo.put("school",checkEmpty(user.getSchool()));
        myInfo.put("career",checkEmpty(user.getCareer()));
        myInfo.put("area",checkEmpty(user.getAddress()));
        myInfo.put("birth", user.getBirth() == null ? "" : ToolForDateTime.dateToString(ToolForDateTime.convertLocalDateToDate(user.getBirth())));
        myInfo.put("briefIntroduction",checkEmpty(user.getBriefIntroduction()));
        myInfo.put("gender",checkEmpty(user.getGender()));
        myInfo.put("sign",checkEmpty(user.getSign()));
        myInfo.put("name",user.getName());
        myInfo.put("avatar",user.getAvatar());
        System.out.println("头像");
        System.out.println(user.getAvatar());
        return ResponseWrapper.markSuccess(myInfo);
    }

    @Override
    public ResponseWrapper getUserDetails(Integer userAidByToken, Integer userAid) {

        // 返回结果
        HashMap<String, Object> result = new HashMap<>();

        // 获取当前登录的这个用户的好友列表（互相关注，他关注的，对方关注的）
        // 这是他关注的用户
        List<UserFollow> userFollows = userFollowMapper.selectList(new LambdaQueryWrapper<UserFollow>()
                .eq(UserFollow::getFollowerAid, userAidByToken)
                .eq(UserFollow::getFollowerType, "用户")
        );
        ArrayList<User> users = new ArrayList<>();
        for (UserFollow userFollow : userFollows) {
            Integer followeredAid = userFollow.getFolloweredAid();
            User user = userMapper.selectById(followeredAid);
            users.add(user);
        }

        // 这是关注他的用户
        List<UserFollow> userFollows1 = userFollowMapper.selectList(new LambdaQueryWrapper<UserFollow>()
                .eq(UserFollow::getFolloweredAid, userAidByToken)
                .eq(UserFollow::getFollowerType, "用户")
        );
        ArrayList<User> users1 = new ArrayList<>();
        for (UserFollow userFollow : userFollows1) {
            Integer followerAid = userFollow.getFollowerAid();
            User user = userMapper.selectById(followerAid);
            users1.add(user);
        }

        // 用于存储互相关注的用户列表
        ArrayList<User> mutualUsers = new ArrayList<>();
        for (User user : users) {
            for (User user1 : users1) {
                if (user.getAid().equals(user1.getAid())){
                    mutualUsers.add(user);
                }
            }
        }

        // 如果互相关注的用户，不够10个，就加上他关注的人
        if(mutualUsers.size() < 10){
            int remaining = 10 - mutualUsers.size();
            for (User user : users) {
                if (!mutualUsers.contains(user)){
                    mutualUsers.add(user);
                    remaining--;
                    if (remaining == 0){
                        break;
                    }
                }
            }
            if (mutualUsers.size() < 10){
                remaining = 10 - mutualUsers.size();
                for (User user : users1) {
                    if (!mutualUsers.contains(user)){
                        mutualUsers.add(user);
                        remaining--;
                        if (remaining == 0) {
                            break;
                        }
                    }
                }
            }
        }
        ArrayList<HashMap<String, Object>> friendsList = new ArrayList<>();
        for (User mutualUser : mutualUsers) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("userAid",mutualUser.getAid());
            map.put("userName",mutualUser.getName());
            map.put("userAvatar",mutualUser.getAvatar());
            friendsList.add(map);
        }
        result.put("friendsList",friendsList);

        // 该用户的全部信息
        User user = userMapper.selectById(userAid);
        result.put("userAid",user.getAid());
        result.put("userName",user.getName());
        result.put("userAvatar",user.getAvatar());
        result.put("bgImageUrl",user.getBgImageUrl());
        // 该用户注册了多少天
        LocalDate now = LocalDate.now();
        Long days = ToolForDateTime.calculateDayNum(user.getCreateTime(), now);
        result.put("registerDay",days + "天");
        // 该用户IP归属地（获取用户的地址）
        String ipAddress;
        if (user.getAddress() == null){
            ipAddress = "无";
        }else if(user.getAddress().equals("")){
            ipAddress = "无";
        }else {
            if (user.getAddress().contains("市")){
                ipAddress = user.getAddress().substring(0, user.getAddress().lastIndexOf("市") + 1);
            }else {
                ipAddress = "无";
            }
        }

        result.put("registerIp",ipAddress);
        // 获取用户签名
        result.put("signature",checkEmpty(user.getSign()));
        // 获取用户的众多标签(性别，年龄，职业，学校)
        ArrayList<HashMap<String, Object>> labels = new ArrayList<>();
        // 用户性别
        if (StringUtils.isNotEmpty(user.getGender()) && StringUtils.isNotBlank(user.getGender())){
            HashMap<String, Object> gender = new HashMap<>();
            gender.put("tagId",labels.size() + 1);
            gender.put("tagName",user.getGender());
            labels.add(gender);
        }
        // 年龄
        if (user.getBirth() != null){
            HashMap<String, Object> ageMap = new HashMap<>();
            ageMap.put("tagId", labels.size() + 1);
            int age = ToolForDateTime.calculateAge(user.getBirth());
            ageMap.put("tagName", age + "岁");
            labels.add(ageMap);
        }

        // 职业
        if (StringUtils.isNotEmpty(user.getCareer()) && StringUtils.isNotBlank(user.getCareer())){
            HashMap<String, Object> careerMap = new HashMap<>();
            careerMap.put("tagId",labels.size() + 1);
            careerMap.put("tagName",user.getCareer());
            labels.add(careerMap);
        }
        // 学校
        if (StringUtils.isNotEmpty(user.getSchool()) && StringUtils.isNotBlank(user.getSchool())){
            HashMap<String, Object> schoolMap = new HashMap<>();
            schoolMap.put("tagId",labels.size() + 1);
            schoolMap.put("tagName",user.getSchool());
            labels.add(schoolMap);
        }
        result.put("tags",labels);

        // 他的关注，粉丝，获赞与收藏
        result.put("guanzhuNum", CommonTool.formatNumber(user.getGuanzhuNum()));
        // 粉丝数量
        result.put("fansNum",CommonTool.formatNumber(user.getFans()));

        // 获赞与收藏（他发的笔记，收获的点赞，收藏数）
        Long zanAndCollectNum = 0L;
        Long thumbNum = 0L;
        Long collectNum = 0L;
        ArrayList<Dynamic> noteList = (ArrayList<Dynamic>) dynamicMapper.selectList(new LambdaQueryWrapper<Dynamic>().eq(Dynamic::getUserAid, userAid));
        for (Dynamic dynamic : noteList) {
            thumbNum += dynamic.getDianZanNum();
            collectNum += dynamic.getCollectNum();
            zanAndCollectNum += dynamic.getDianZanNum();
            zanAndCollectNum += dynamic.getCollectNum();
        }
        result.put("zanNum", CommonTool.formatNumber(zanAndCollectNum.intValue()));
        ArrayList<HashMap<String, Object>> likeAndCollect = getHashMaps(noteList, thumbNum, collectNum);
        result.put("likeAndCollect",likeAndCollect);

        // 按钮文字（关注，已关注，回关）
        UserFollow userFollow = userFollowMapper.selectOne(new LambdaQueryWrapper<UserFollow>()
                .eq(UserFollow::getFollowerAid,userAidByToken)
                .eq(UserFollow::getFolloweredAid,userAid)
        );
        UserFollow userFollow1 = userFollowMapper.selectOne(new LambdaQueryWrapper<UserFollow>()
                .eq(UserFollow::getFolloweredAid,userAidByToken)
                .eq(UserFollow::getFollowerAid,userAid)
        );
        if (userFollow != null && userFollow1 != null){
            result.put("guanzhuText", "已关注");
        }else if(userFollow == null && userFollow1 != null){
            result.put("guanzhuText", "回关");
        }else if (userFollow != null && userFollow1 == null){
            result.put("guanzhuText", "已关注");
        }else {
            result.put("guanzhuText", "关注");
        }

        // 他发布的所有笔记（公开的让所有人看的）
        ArrayList<HashMap<String, Object>> notes = new ArrayList<>();
        List<Dynamic> dynamics = dynamicMapper.selectList(new LambdaQueryWrapper<Dynamic>()
                .eq(Dynamic::getUserAid, userAid)
        );
        for (Dynamic dynamic : dynamics) {
            HashMap<String, Object> note = new HashMap<>();
            note.put("noteAid",dynamic.getAid());
            note.put("isVedio",dynamic.getMedioType().equals("video"));
            if (dynamic.getMedioType().equals("video")){
                note.put("url",checkEmpty(dynamic.getDynamicVideo()));
            }else {
                String imgs = dynamic.getDynamicImgs();
                if (!imgs.equals("") && imgs != null){
                    if (imgs.contains(";")){
                        String[] imgArr = imgs.split(";");
                        note.put("url",imgArr[0]);
                    }else {
                        note.put("url",imgs);
                    }
                }else {
                    note.put("url","");
                }
            }
            note.put("videoCover",dynamic.getMedioType().equals("video") ? checkEmpty(dynamic.getDynamicCover()) : "");
            note.put("title",checkEmpty(dynamic.getDynamicName()));
            note.put("releaseTime",ToolForDateTime.LocalDateTimeToStringText(dynamic.getCreateTime()));
            List<ThumbsUp> thumbsUps = thumbsUpMapper.selectList(new LambdaQueryWrapper<ThumbsUp>()
                    .eq(ThumbsUp::getThumbsUpUserAid,userAidByToken)
                    .eq(ThumbsUp::getThumbsUpedAid,dynamic.getAid())
                    .eq(ThumbsUp::getType, "笔记")
            );
            note.put("isLike",thumbsUps.size() > 0);
            note.put("likeCount",dynamic.getDianZanNum());
            notes.add(note);
        }
        result.put("notes",notes);

        // 他收藏的笔记
        ArrayList<HashMap<String, Object>> CollectNoteMap = new ArrayList<>();
        List<Collect> userCollectNotes = collectMapper.selectList(new LambdaQueryWrapper<Collect>()
                .eq(Collect::getCollectType,"笔记")
                .eq(Collect::getUserAid,userAid)
        );
        for (Collect userCollectNote : userCollectNotes) {
            HashMap<String, Object> note = new HashMap<>();
            Long dynamicAid = userCollectNote.getCollectAid();
            Dynamic dynamic = dynamicMapper.selectById(dynamicAid);
            note.put("noteAid",dynamic.getAid());
            note.put("isVedio",dynamic.getMedioType().equals("video"));
            if (dynamic.getMedioType().equals("video")){
                note.put("url",checkEmpty(dynamic.getDynamicVideo()));
            }else {
                String imgs = dynamic.getDynamicImgs();
                if (!imgs.equals("") && imgs != null){
                    if (imgs.contains(";")){
                        String[] imgArr = imgs.split(";");
                        note.put("url",imgArr[0]);
                    }else {
                        note.put("url",imgs);
                    }
                }else {
                    note.put("url","");
                }
            }
            note.put("videoCover",dynamic.getMedioType().equals("video") ? checkEmpty(dynamic.getDynamicCover()) : "");
            note.put("title",checkEmpty(dynamic.getDynamicName()));
            User user1 = userMapper.selectById(dynamic.getUserAid());
            note.put("authorAvatar",user1.getAvatar());
            note.put("authorUserName",user1.getName());
            List<ThumbsUp> thumbsUps = thumbsUpMapper.selectList(new LambdaQueryWrapper<ThumbsUp>()
                    .eq(ThumbsUp::getThumbsUpUserAid,userAidByToken)
                    .eq(ThumbsUp::getThumbsUpedAid,dynamic.getAid())
                    .eq(ThumbsUp::getType, "笔记")
            );
            note.put("isLike",thumbsUps.size() > 0);
            note.put("likeCount",dynamic.getDianZanNum());
            CollectNoteMap.add(note);
        }
        result.put("userCollectNotes",CollectNoteMap);

        // 他收藏的商品
        ArrayList<HashMap<String, Object>> CollectGoodsMapList = new ArrayList<>();
        List<Collect> userCollectGoods = collectMapper.selectList(new LambdaQueryWrapper<Collect>()
                .eq(Collect::getCollectType,"商品")
                .eq(Collect::getUserAid,userAid)
        );
        for (Collect userCollectGood : userCollectGoods) {
            Goods goods = goodsMapper.selectById(userCollectGood.getCollectAid());
            HashMap<String, Object> collectGoodsMap = getStringObjectHashMap(goods);
            CollectGoodsMapList.add(collectGoodsMap);
        }
        result.put("userCollectGoods",CollectGoodsMapList);
        return ResponseWrapper.markSuccess(result);
    }

    @Override
    public ResponseWrapper getFollowsAndFans(Integer userAidByToken, Integer userAid) {

        // 返回结果
        HashMap<String,Object> result = new HashMap<>();

        // 他的粉丝
        List<UserFollow> userFollows = userFollowMapper.selectList(new LambdaQueryWrapper<UserFollow>()
                .eq(UserFollow::getFolloweredAid,userAid)
                .eq(UserFollow::getFollowerType,"用户")
        );
        ArrayList<HashMap<String,Object>> fans = new ArrayList<>();
        for (UserFollow userFollow : userFollows) {
            HashMap<String,Object> map = new HashMap<>();
            User user = userMapper.selectById(userFollow.getFollowerAid());
            map.put("userAid",user.getAid());
            map.put("avatar",user.getAvatar());
            map.put("userName",user.getName());
            UserFollow userFollow1 = userFollowMapper.selectOne(new LambdaQueryWrapper<UserFollow>()
                    .eq(UserFollow::getFolloweredAid,user.getAid())
                    .eq(UserFollow::getFollowerAid,userAidByToken)
                    .eq(UserFollow::getFollowerType,"用户")
            );
            if (userFollow1 != null){
                map.put("btnText","聊天");
            }else {
                map.put("btnText","关注");
            }
            fans.add(map);
        }
        result.put("myFans",fans);

        // 他的关注
        ArrayList<HashMap<String,Object>> follows = new ArrayList<>();
        List<UserFollow> userFollows1 = userFollowMapper.selectList(new LambdaQueryWrapper<UserFollow>()
                .eq(UserFollow::getFollowerAid,userAid)
                .eq(UserFollow::getFollowerType,"用户")
        );
        for (UserFollow userFollow : userFollows1) {
            HashMap<String,Object> map = new HashMap<>();
            User user = userMapper.selectById(userFollow.getFolloweredAid());
            map.put("userAid",user.getAid());
            map.put("avatar",user.getAvatar());
            map.put("userName",user.getName());
            UserFollow userFollow1 = userFollowMapper.selectOne(new LambdaQueryWrapper<UserFollow>()
                    .eq(UserFollow::getFolloweredAid,user.getAid())
                    .eq(UserFollow::getFollowerAid,userAidByToken)
                    .eq(UserFollow::getFollowerType,"用户")
            );
            if (userFollow1 != null){
                map.put("btnText","聊天");
            }else {
                map.put("btnText","关注");
            }
            follows.add(map);
        }
        result.put("myFollows",follows);
        return ResponseWrapper.markSuccess(result);
    }

    @Override
    public ResponseWrapper loginByCode(LoginByCodeParam param) {
        List<User> userList = userMapper.selectList(null);
        String name = "疆屿用户" + userList.size() + 1;
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getPhone,param.getPhone()));
        if (user == null){
            // 如果没有这个手机号的用户，就新增一个
            int insert = userMapper.insert(new User(){{
                setName(name);
                setPhone(param.getPhone());
                setRecords(0);
                // 默认头像（已经存储在oss里了）
                setAvatar("https://app-jy-mobile.oss-cn-hangzhou.aliyuncs.com/static/user/default_user_avatar.png");
                setPassword("123456");
                setGuanzhuNum(0);
                setFans(0);
                setCollectNum(0);
                setPosts(0);
            }});
            if (insert > 0){
                User user1 = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getPhone,param.getPhone()));
                // 制作token
                Map<String, String> map = new HashMap<>();
                map.put("aid", user1.getAid().toString());
                String token = JwtUtil.getToken(map);
                return ResponseWrapper.markSuccess(token);
            }else {
                return ResponseWrapper.markError();
            }
        }else {
            // 如果该用户存在，就直接制作token，登陆成功
            // 制作token
            Map<String, String> map = new HashMap<>();
            map.put("aid", user.getAid().toString());
            String token = JwtUtil.getToken(map);
            return ResponseWrapper.markSuccess(token);
        }
    }

    @Override
    public ResponseWrapper getMyBusinessCard(Integer userAidByToken) {
        User user = userMapper.selectById(userAidByToken);
        HashMap<String, Object> result = new HashMap<>();
        result.put("userAid",user.getAid());
        result.put("myUserAvatar",user.getAvatar());
        result.put("myUserName",user.getName());
        return ResponseWrapper.markSuccess(result);
    }

    @Override
    public ResponseWrapper getCollectList(Integer userAidByToken, Integer userAid) {

        // 返回结果
        HashMap<String, Object> result = new HashMap<>();

        // 收藏的笔记
        List<Collect> collects = collectMapper.selectList(new LambdaQueryWrapper<Collect>()
                .eq(Collect::getCollectType, "笔记")
                .eq(Collect::getUserAid, userAid)
        );
        if (collects.size() > 0){
            ArrayList<HashMap<String, Object>> notes = new ArrayList<>();
            for (Collect collect : collects) {
                HashMap<String, Object> map = new HashMap<>();
                Dynamic dynamic = dynamicMapper.selectById(collect.getCollectAid());
                map.put("noteAid",dynamic.getAid());
                map.put("isVedio",dynamic.getMedioType().equals("video"));
                if (dynamic.getMedioType().equals("image")){
                    String dynamicImgs = dynamic.getDynamicImgs();
                    if (dynamicImgs.contains(";")){
                        String[] split = dynamicImgs.split(";");
                        map.put("url",split[0]);
                    }else {
                        map.put("url",dynamicImgs);
                    }
                }else {
                    map.put("url",dynamic.getDynamicVideo());
                }
                map.put("title",dynamic.getDynamicName().length() > 15 ? dynamic.getDynamicName().substring(0,15) + "..." : dynamic.getDynamicName());
                Integer userAid1 = dynamic.getUserAid();
                User user = userMapper.selectById(userAid1);
                map.put("authorAvatar",user.getAvatar());
                map.put("authorUserName",user.getName());
                List<ThumbsUp> thumbsUps = thumbsUpMapper.selectList(new LambdaQueryWrapper<ThumbsUp>()
                        .eq(ThumbsUp::getThumbsUpUserAid, userAidByToken)
                        .eq(ThumbsUp::getThumbsUpedAid, dynamic.getAid())
                        .eq(ThumbsUp::getType, "笔记")
                );
                map.put("isLike",thumbsUps.size() > 0);
                map.put("likeCount",dynamic.getDianZanNum());
                notes.add(map);
            }
            result.put("notes",notes);
        }else {
            result.put("notes",new ArrayList<>());
        }


        // 收藏的商品
        List<Collect> goods = collectMapper.selectList(new LambdaQueryWrapper<Collect>()
                .eq(Collect::getCollectType, "商品")
                .eq(Collect::getUserAid, userAid)
        );
        if (goods.size() > 0){
            ArrayList<HashMap<String, Object>> goodsList = new ArrayList<>();
            for (Collect good : goods) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("goodsAid",good.getCollectAid());
                Goods goods1 = goodsMapper.selectById(good.getCollectAid());
                map.put("goodImg",goods1.getGoodsMainImage());
                map.put("goodsName",goods1.getGoodsName());
                map.put("goodsPrice","￥" + goods1.getGoodsPrice());
                goodsList.add(map);
            }
            result.put("goods",goodsList);
        }else {
            result.put("goods",new ArrayList<>());
        }
        return ResponseWrapper.markSuccess(result);
    }

    @Override
    public ResponseWrapper getMyPost(Integer userAidByToken, Integer userAid) {

        List<Dynamic> dynamics = dynamicMapper.selectList(new LambdaQueryWrapper<Dynamic>()
                .eq(Dynamic::getUserAid, userAid)
                .eq(Dynamic::getIsRelease, true)
        );
        if (dynamics.size() > 0){
            // 返回结果
            ArrayList<HashMap<String, Object>> result = new ArrayList<>();
            for (Dynamic dynamic : dynamics) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("noteAid",dynamic.getAid());
                map.put("isVedio",dynamic.getMedioType().equals("video"));
                if (dynamic.getMedioType().equals("image")){
                    String dynamicImgs = dynamic.getDynamicImgs();
                    if (dynamicImgs.contains(";")){
                        String[] split = dynamicImgs.split(";");
                        map.put("url",split[0]);
                    }else {
                        map.put("url",dynamicImgs);
                    }
                }else {
                    map.put("url",dynamic.getDynamicVideo());
                }
                map.put("title",dynamic.getDynamicName().length() > 15 ? dynamic.getDynamicName().substring(0,15) + "..." : dynamic.getDynamicName());
                map.put("releaseTime",ToolForDateTime.LocalDateTimeToStringText(dynamic.getCreateTime()));
                User user = userMapper.selectById(dynamic.getUserAid());
                List<ThumbsUp> thumbsUps = thumbsUpMapper.selectList(new LambdaQueryWrapper<ThumbsUp>()
                        .eq(ThumbsUp::getThumbsUpUserAid, userAidByToken)
                        .eq(ThumbsUp::getThumbsUpedAid, dynamic.getAid())
                        .eq(ThumbsUp::getType, "笔记")
                );
                map.put("isLike",thumbsUps.size() > 0);
                map.put("likeCount",dynamic.getDianZanNum());
                map.put("commentCount",dynamic.getCommentNum());
                result.add(map);
            }
            return ResponseWrapper.markSuccess(result);
        }else {
            return ResponseWrapper.markSuccess(new ArrayList<>());
        }
    }

    private static ArrayList<HashMap<String, Object>> getHashMaps(ArrayList<Dynamic> noteList, Long thumbNum, Long collectNum) {
        ArrayList<HashMap<String, Object>> likeAndCollect = new ArrayList<>();
        // 当前发布的笔记数
        HashMap<String, Object> noteMap = new HashMap<>();
        noteMap.put("text","当前发布的笔记数");
        noteMap.put("num", CommonTool.formatNumber(noteList.size()));
        likeAndCollect.add(noteMap);
        // 当前获得的点赞数
        HashMap<String, Object> noteMap1 = new HashMap<>();
        noteMap1.put("text","当前获得点赞数");
        noteMap1.put("num", CommonTool.formatNumber(thumbNum.intValue()));
        likeAndCollect.add(noteMap1);
        // 当前获得收藏数
        HashMap<String, Object> noteMap2 = new HashMap<>();
        noteMap2.put("text","当前获得点赞数");
        noteMap2.put("num", CommonTool.formatNumber(collectNum.intValue()));
        likeAndCollect.add(noteMap2);
        return likeAndCollect;
    }

    private static HashMap<String, Object> getStringObjectHashMap(Goods goods) {
        HashMap<String, Object> collectGoodsMap = new HashMap<>();
        collectGoodsMap.put("goodsAid", goods.getAid());
        if (goods.getGoodsMainImage() == null || goods.getGoodsMainImage().equals("")){
            collectGoodsMap.put("goodImg", goods.getGoodsSwipers().contains(";") ? goods.getGoodsSwipers().substring(0, goods.getGoodsSwipers().indexOf(";")) : goods.getGoodsSwipers());
        }else {
            collectGoodsMap.put("goodImg", goods.getGoodsMainImage());
        }
        collectGoodsMap.put("goodsName", goods.getGoodsName());
        collectGoodsMap.put("goodsPrice", goods.getGoodsPrice());
        return collectGoodsMap;
    }


    private String checkEmpty(String str){
        return (str == null || str.equals("")) ? "" : str;
    }



}
